// Copyright (c) 2025 Shenzhen Kaihong Digital Industry Development Co., Ltd.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use std::path::{Path, PathBuf};

use clap::Parser;
use indicatif::MultiProgress;

use crate::{database::{init_system_config, local::{CACHE_ROOT, CONFIG_ROOT, PKGS_ROOT}, ShellConfig}, FerriumCommand};

#[derive(Debug, Parser)]
pub struct InitCommand {
    /// The path to system config directory, default is `/etc/ferrium`
    #[arg(short, long)]
    config_root: Option<PathBuf>,
    /// The path to the installed pkgs directory, default is `/pkg`
    #[arg(short, long)]
    pkgs_root: Option<PathBuf>,
    /// The path to the cache directory, default is `$XDG_CACHE_HOME or $HOME/.cache`
    #[arg(long)]
    cache_root: Option<PathBuf>,
    /// The specified shell configs to be generated
    #[arg(short, long, default_value = "bash", num_args = 0..)]
    shell_configs: Vec<ShellConfig>,
    /// If specified, the system config will be generated from the specified local config directory.
    /// Otherwise the system config will be downloaded automatically.
    #[arg(short, long)]
    local_config: Option<PathBuf>,
    /// Force overwrite existing system config
    #[arg(short, long)]
    force: bool,
}

impl FerriumCommand for InitCommand {
    async fn run(self, _multi_progress: MultiProgress) -> anyhow::Result<()> {
        let config_root = self.config_root.unwrap_or_else(|| Path::new(CONFIG_ROOT.as_str()).to_path_buf());
        let pkgs_root = self.pkgs_root.unwrap_or_else(|| PKGS_ROOT.to_path_buf());
        let cache_root = self.cache_root.unwrap_or_else(|| CACHE_ROOT.to_path_buf());
        init_system_config(
            config_root,
            pkgs_root,
            cache_root,
            &self.shell_configs,
            self.local_config,
            self.force,
        ).await?;
        Ok(())
    }
}
